package org.sunrise.game.game.modules;

import com.alibaba.fastjson2.TypeReference;
import lombok.Getter;
import lombok.Setter;
import org.sunrise.game.game.logic.map.GameMap;
import org.sunrise.game.game.logic.map.MapManager;
import org.sunrise.game.game.proto.MapProto;
import org.sunrise.game.game.proto.TopicProto;

import java.util.Random;

@Getter
@Setter
public class MapModule extends BaseModule {
    private int mapId;
    private int lastMapId;
    private int mapPostX;
    private int mapPostY;
    private int mapPostZ;
    private Random random = new Random();

    public MapModule(String humanId) {
        super(humanId);
    }

    @Override
    public void init() {
        mapId = 0;
        mapPostX = random.nextInt(600);
        mapPostY = random.nextInt(600);
        mapPostZ = 0;
    }

    @Override
    public void load() {
        getDbData("id", new TypeReference<Integer>() {}, value -> lastMapId = value);
        getDbData("mapPostX", new TypeReference<Integer>() {}, value -> mapPostX = value);
        getDbData("mapPostY", new TypeReference<Integer>() {}, value -> mapPostY = value);
        getDbData("mapPostZ", new TypeReference<Integer>() {}, value -> mapPostZ = value);
    }

    @Override
    public void save() {
        putDbData("id", mapId);
        putDbData("mapPostX", mapPostX);
        putDbData("mapPostY", mapPostY);
        putDbData("mapPostZ", mapPostZ);
    }

    @Override
    public void sendToClient() {
        getHuman().sendMsg(TopicProto.TOPIC.TOPIC_TYPE_MAP_VALUE, MapProto.FROM_SERVER.S2C_LastMap_VALUE,
                MapProto.MS2C_LastMap.newBuilder().setId(lastMapId).setMapPostX(mapPostX).setMapPostY(mapPostY).setMapPostZ(mapPostZ));
    }

    public void updatePosition(int x, int y, int z) {
        this.mapPostX = x;
        this.mapPostY = y;
        this.mapPostZ = z;
    }

    public void leaveMap() {
        if (mapId == 0) {
            return;
        }
        GameMap gameMap = MapManager.instance.getMap(mapId);
        if (gameMap == null) {
            return;
        }

        gameMap.humanObjectLeave(this.getHumanId());
    }
}
